package com.ellecity06.common.widgets.dialog

import android.app.Activity
import android.util.Log
import androidx.annotation.DrawableRes
import com.ellecity06.common.R
import com.ellecity06.common.base.BaseDialog
import com.ellecity06.common.databinding.DialogLoadingBinding
import com.ellecity06.common.ktx.dp2px
import com.ellecity06.common.utils.logD
import com.ellecity06.common.widgets.drawble.IosLoadingDrawable

/**
 * @author ellecity06
 * @time 2023/4/1 16:07
 * @des
 */
class LoadingDialog(context: Activity) : BaseDialog<DialogLoadingBinding>(context) {
    private val loadingDrawable: IosLoadingDrawable by lazy { IosLoadingDrawable(context) }
    private val dialogSize: Int by lazy { context.dp2px(150) }
    override fun inflaterViewBinding(): DialogLoadingBinding =
        DialogLoadingBinding.inflate(layoutInflater)

    override val widthP: Float
        get() = 0.4F
    override val dimAmount: Float
        get() = 0.1f

    override fun initialize() {
        binding.ivLoading.setImageDrawable(loadingDrawable)
    }


    fun show(text: String) {
        binding.ivLoading.setImageDrawable(loadingDrawable)
        binding.tvLoading.text = text
        this.show()
    }

    /**
     * loading 成功
     * @param resId 成功的图标
     * @param text 成功的文本
     */
    fun success(
        @DrawableRes resId: Int = 0,
        text: String = "加载成功！",
        delay: Long = 100
    ) {
        setLoadState(resId, text, delay)


    }

    /**
     * loading 失败
     * @param resId 成功的图标
     * @param text 成功的文本
     */
    fun fail(
        @DrawableRes resId: Int = 0,
        text: String = "加载失败！",
        delay: Long = 100
    ) {
        setLoadState(resId, text, delay)
    }

    private fun setLoadState(resId: Int, text: String, delay: Long) {
        loadingDrawable.cancel()
        if (resId != 0)
            binding.ivLoading.setImageResource(resId)
        binding.tvLoading.text = text
        if (delay > 0) {
            binding.ivLoading.postDelayed({
                dismiss()
            }, delay)
        } else {
            dismiss()
        }
    }


    override fun show() {
        loadingDrawable.start()
        super.show()
    }

    override fun dismiss() {
        loadingDrawable.cancel()
        super.dismiss()
    }
}